package com.dycong.common.leetcode;

import java.util.LinkedList;
import java.util.List;

/**
 * todo 给定一个字符串,找出其中最长的回文串-暴力法
 */
public class LongestPalindrome_5 {

    public static void main(String[] args) {
        String str = "babasdasdasdaasad5465465461sdadasdasdsadasdaascxzczxczxczcd";
        LongestPalindrome_5 c = new LongestPalindrome_5();
        if (c.isPlalindromeStr(str)) {
            System.out.println(str);
        } else {
            c.printPlanindromeStr(str, str.length() - 2);
        }
    }

    /**
     * 判断制定字符串是不是回文字符串
     *
     * @param str
     * @return
     */
    public boolean isPlalindromeStr(String str) {
        char[] strArray = str.toCharArray();
        int i = 0;
        int j = str.length() - 1;
        while (i <= j) {
            if (strArray[i] == (strArray[j])) {
                i++;
                j--;
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取指定字符串长度为length的所有子串
     *
     * @param str
     * @param length
     * @return
     */
    public List<String> getAllSubString(String str, int length) {
        List<String> listStr = new LinkedList<String>();
        // int count = str.length() - length;
        int len = str.length();
        int i = 0;
        while (i + length <= len) {
            listStr.add(str.substring(i, i + length));
            i++;
        }
        return listStr;
    }

    /**
     * 打印出回文字符串
     *todo 递归
     * @param str
     * @param length
     */
    public void printPlanindromeStr(String str, int length) {
        boolean flag = false;
        List<String> allSubString = getAllSubString(str, length);
        for (String string : allSubString) {
            if (isPlalindromeStr(string)) {
                System.out.println(string);
                System.out.println(string.length());
                flag = true;
                break;
            }
        }
        if (!flag) {
            printPlanindromeStr(str, length - 1);
        }
    }

}
